import {reactive, ref} from "vue";
import {logout, updatePassword} from "@/api/manager.js";
import {showModal, toast} from "@/composables/utils.js";
import {useRouter} from "vue-router";
import {useUserInfoStore} from "@/stores/userInfo.js";


export function useRepassword(){
    const router = useRouter();
    const store = useUserInfoStore();
    const formDrawerRef = ref(null);
    const form = reactive({
        oldpassword: "",
        password: '',
        repassword: '',
    })

    const rules = reactive({
        oldpassword: [
            { required: true, message: '旧密码不能为空', trigger: 'blur' }
        ],
        password: [
            { required: true, message: '新密码不能为空', trigger: 'blur' }
        ],
        repassword: [
            { required: true, message: '确认密码不能为空', trigger: 'blur' }
        ],
    })
    const formRef = ref(null);

    const onSubmit = () => {
        formRef.value.validate((valid) => {
            if (!valid) {
                return false
            }
            formDrawerRef.value.showLoading()
            updatePassword(form.oldpassword, form.password,form.repassword)
                .then(res => {
                    toast("修改密码成功,请重新登录")
                    store.logouts()
                    router.push('/login')
                }).finally(() => {
                formDrawerRef.value.hideLoading()
            })
        })
    }
    return {
        form,
        rules,
        formDrawerRef,
        formRef,
        onSubmit,
        router,
        store
    }
}


export function useLogout(){
    const router = useRouter();
    const store = useUserInfoStore();
    function handleLogout() {

        showModal("是否要退出登录？").then(res => {
            logout().finally(() => {
                //清除当前用户状态
                store.logouts()
                //跳转回登录页
                router.push('/login')
                //提示退出登录成功
                toast("退出登录成功")
            })
            console.log("logout")
        })
    }
    return {
        handleLogout
    }
}